﻿using Common;
using Domain.Repositories;
using Infrastructure;
using MediatR;

namespace Application.User
{
    public record LoginCommand(string UserName, string Password) : IRequest<Result<UserToken>>;

    public class LoginCommandHandler(IUserRepository userRepository, TokenProvider tokenProvider) : IRequestHandler<LoginCommand, Result<UserToken>>
    {
        public async Task<Result<UserToken>> Handle(LoginCommand request, CancellationToken cancellationToken)
        {
            var user = await userRepository.GetAsync(u=>u.LoginName==request.UserName);
            if (user is null || !user.HasPassword())
            {
                return ResultBuilder.Fail<UserToken>(null, "账号不存在，联系管理员处理");
            }

            if (HashHelper.ComputeMD5Hash(request.Password + ConstKeyNames.MD5Salt) != user.Password)
            {
                return ResultBuilder.Fail<UserToken>(null, "账号或密码错误");
            }

            var token = tokenProvider.CreateToken(user.Id.ToString(), user.Email);

            return ResultBuilder.Success(token);

        }
    }
}
